<?php


namespace app\tickets\controller;


use app\api\controller\Commondevice;
use app\api\controller\Test;
use app\common\controller\Common;
use app\index\controller\Base;
use think\Db;
use think\Exception;

class Finance extends Base
{

    /**
     * 售票明细
     * @return mixed
     * @author zhixuedong
     * @date 2021/2/1/001
     */
    public function index(){
        $common = new Common();
        $where = "1=1";
        $nowtime = date("Y-m-d");
        if(!empty($_GET['status'])){
            if($_GET['status']==1){
                $where .= " and status=1 and end_time > '".$nowtime."'";
            }elseif($_GET['status']==-1){
                $where .=" and status = 0";
            }else{
                $where .= " and (status=2 or end_time<'".$nowtime."')";
            }
        }

        if(!empty($_GET['keyword'])){
            $where .=" and signcode like '%".$_GET['keyword']."%'";
        }

        if(!empty($_POST['type'])){
            try {
                $detail = Db::name("tickets_list")->where(['id'=>$_POST['id']])->find();
                $Commondevice = new Test();

                $personsCreate['employeeNo'] = $detail['signcode'];
                if(!empty($detail['IDcard'])){
                    $cardNos = [$detail['IDcard'],$detail['signcode']]; //$order['IDcard']
                }else{
                    $cardNos = [$detail['signcode']];
                }
                $personsCreate['personName'] = empty($detail['name'])?"欢迎光临":$detail['name'];

                $startTime = date("Y-m-d\T00:00:01P",strtotime($detail['effective_time']));
                $endtTime = date("Y-m-d\T23:59:59P",strtotime($detail['end_time']));
                $personsCreate['validBeginTime'] = $startTime;
                $personsCreate['validEndTime'] = $endtTime;
                $cardValue = $Commondevice->cardAdd($personsCreate,$cardNos);

                if(!empty($faceUrl)){
                    $personsCreate['faceImageBase64'] = $faceUrl;
                    $cardValue = $Commondevice->personsUpdate($personsCreate);
                }
                if(!empty($detail['face']) & $detail['face']!='null'){
                    $personsCreate['faceImageBase64'] = $detail['face'];
                    $cardValue = $Commondevice->personsUpdate($personsCreate);
                }

                if($cardValue!==true){
                    throw new Exception($cardValue['message']);
                }

                $black['code'] = 0;
                $black['msg'] = "推送成功";
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;

        }

        if (!empty($_GET['type'])) {

            $tickets_type = $common->publicAttribute("tickets_type");
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("tickets_list")->limit($start, $limit)->where($where)
                    ->order("id desc")->select();
                foreach ($list as $k => $v) {
                    $list[$k]['addtime'] = date("Y-m-d H:i:s", $v['addtime']);
                    $status_name = "正常";
                    if($v['status'] == 2){
                        $status_name = "作废";
                    }
                    if($nowtime > $v['end_time']){
                        $status_name = "作废";
                    }
                    if($v['status'] == 0){
                        $status_name = "未生效";
                    }
                    $list[$k]['status_name'] = $status_name;
                    $list[$k]['type'] = $tickets_type[$v['type']];
                }
                $count = Db::name("tickets_list")->limit($start, $limit)->where($where)->count("*");
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }

        return $this->fetch('index');
    }



    /**
     * 售票明细
     * @return mixed
     * @author zhixuedong
     * @date 2021/2/1/001
     */
    public function tickets(){
        $common = new Common();
        $where = "1=1";
        $nowtime = date("Y-m-d");
        if(!empty($_GET['status'])){
            if($_GET['status']==1){
                $where .= " and status=1 and end_time > '".$nowtime."'";
            }elseif($_GET['status']==-1){
                $where .=" and status = 0";
            }else{
                $where .= " and (status=2 or end_time<'".$nowtime."')";
            }
        }

        if(!empty($_GET['keyword'])){
            $where .=" and signcode like '%".$_GET['keyword']."%'";
        }


        if (!empty($_GET['type'])) {
            $tickets_type = $common->publicAttribute("tickets_type");
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("tickets_list")->limit($start, $limit)->where($where)
                    ->order("id desc")->select();
                foreach ($list as $k => $v) {
                    $list[$k]['addtime'] = date("Y-m-d H:i:s", $v['addtime']);
                    $status_name = "正常";
                    if($v['status'] == 2){
                        $status_name = "作废";
                    }
                    if($nowtime > $v['end_time']){
                        $status_name = "作废";
                    }
                    if($v['status'] == 0){
                        $status_name = "未生效";
                    }
                    $list[$k]['status_name'] = $status_name;
                    $list[$k]['type'] = $tickets_type[$v['type']];
                }
                $count = Db::name("tickets_list")->limit($start, $limit)->where($where)->count("*");
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }

        return $this->fetch('tickets');
    }

    //当日
    public function publicCount($newData,$type=0){
        $common = new Common();
        $tickets_order = "tickets_order";
        if(empty($type)){
            $where['currentDate'] = $newData;
        }else{
            $where['currentDate'] = ['like',"%".date("Ym",strtotime($newData))."%"];
        }
        $where['is_pay'] = 2;
        //总收入
        $general = $common->public_select($tickets_order,$where)->sum("total_amount");
        $general = empty($general)?0:$general;



        //微信收入 wechat
        if(empty($type)){
            $where1['currentDate'] = $newData;
        }else{
            $where1['currentDate'] = ['like',"%".date("Ym",strtotime($newData))."%"];
        }
        $where1['is_pay'] = 2;
        $where1['pay_type'] = 1;
        $wechat = $common->public_select($tickets_order,$where1)->sum("total_amount");
        $wechat = empty($wechat)?0:$wechat;

        //余额收入 balance
        if(empty($type)){
            $where2['currentDate'] = $newData;
        }else{
            $where2['currentDate'] = ['like',"%".date("Ym",strtotime($newData))."%"];
        }
        $where2['is_pay'] = 2;
        $where2['pay_type'] = 2;
        $balance = $common->public_select($tickets_order,$where2)->sum("total_amount");
        $balance = empty($balance)?0:$balance;

        //现金收入 balance
        if(empty($type)){
            $where3['currentDate'] = $newData;
        }else{
            $where3['currentDate'] = ['like',"%".date("Ym",strtotime($newData))."%"];
        }
        $where3['is_pay'] = 2;
        $where3['pay_type'] = 3;
        $delivery = $common->public_select($tickets_order,$where3)->sum("total_amount");
        $delivery = empty($delivery)?0:$delivery;

        //支付宝收入 balance
        if(empty($type)){
            $where4['currentDate'] = $newData;
        }else{
            $where4['currentDate'] = ['like',"%".date("Ym",strtotime($newData))."%"];
        }
        $where4['is_pay'] = 2;
        $where4['pay_type'] = 4;
        $alipay = $common->public_select($tickets_order,$where4)->sum("total_amount");
        $alipay = empty($alipay)?0:$alipay;

        if(empty($type)){
            return ['general'=>$general,'wechat'=>$wechat,'balance'=>$balance,'delivery'=>$delivery,'alipay'=>$alipay];
        }else{
            return ['monthgeneral'=>$general,'monthwechat'=>$wechat,'monthbalance'=>$balance,'monthdelivery'=>$delivery,'monthalipay'=>$alipay];
        }
    }


    public function get_weekinfo_by_date($date) {
        $idx = strftime("%u", strtotime($date));
        $mon_idx = $idx - 1;
        $sun_idx = $idx - 7;
        return array(
            'week_start_day' => strftime('%Y-%m-%d', strtotime($date) - $mon_idx * 86400),
            'week_end_day' => strftime('%Y-%m-%d', strtotime($date) - $sun_idx * 86400),
        );
    }

    //本周
    public function weekCount($newData){
        $value = $this->get_weekinfo_by_date($newData);
        $start = date("Ymd",strtotime($value['week_start_day']));
        $end = date("Ymd",strtotime($value['week_end_day']));
        $common = new Common();
        $tickets_order = "tickets_order";
        $where['currentDate'] = ['between',[$start,$end]];
        $where['is_pay'] = 2;
        //总收入
        $general = $common->public_select($tickets_order,$where)->sum("total_amount");
        $general = empty($general)?0:$general;

        //微信收入 wechat
        $where1['currentDate'] = ['between',[$start,$end]];
        $where1['is_pay'] = 2;
        $where1['pay_type'] = 1;
        $wechat = $common->public_select($tickets_order,$where1)->sum("total_amount");
        $wechat = empty($wechat)?0:$wechat;

        //余额收入 balance
        $where2['currentDate'] = ['between',[$start,$end]];
        $where2['is_pay'] = 2;
        $where2['pay_type'] = 2;
        $balance = $common->public_select($tickets_order,$where2)->sum("total_amount");
        $balance = empty($balance)?0:$balance;

        //现金收入 balance
        $where3['currentDate'] = ['between',[$start,$end]];
        $where3['is_pay'] = 2;
        $where3['pay_type'] = 3;
        $delivery = $common->public_select($tickets_order,$where3)->sum("total_amount");
        $delivery = empty($delivery)?0:$delivery;

        //支付宝收入 balance
        $where4['currentDate'] = ['between',[$start,$end]];
        $where4['is_pay'] = 2;
        $where4['pay_type'] = 4;
        $alipay = $common->public_select($tickets_order,$where4)->sum("total_amount");
        $alipay = empty($alipay)?0:$alipay;

        return ['weegeneral'=>$general,'weewechat'=>$wechat,'weebalance'=>$balance,'weedelivery'=>$delivery,'weealipay'=>$alipay];
    }

    /**
     * 售票汇总
     * @return mixed
     * @author zhixuedong
     * @date 2021/1/26/026
     */
    public function gather(){

        $newData = date("Ymd");
        //统计当日总收入

        $value = $this->publicCount($newData);
        $this->assign($value);

        $monthvalue = $this->publicCount($newData,1);
        $this->assign($monthvalue);

        $ewwvalue = $this->weekCount($newData);
        $this->assign($ewwvalue);

        $latelyWhere['is_pay'] = 2;
        //最近七天
        $lately = Db::name("tickets_order")->where($latelyWhere)->field("sum(total_amount) as total,currentDate")->limit(15)->group('currentDate')->order("currentDate asc")->select();

        $latelyValue = [];
        $latelyGeneral = [];
        $latelyWechat = [];
        $latelyBalance = [];
        $latelyDelivery = [];
        $latelyAlipayt = [];
        foreach ($lately as $k=>$v){
            $latelyValue[] = date("Y年m月d日",strtotime($v['currentDate']));
            $latelyGeneral[] = empty($v['total'])?0:$v['total'];
            //微信收入
            $latelyWechatVal = Db::name("tickets_order")->where(['pay_type'=>1,'currentDate'=>$v['currentDate']])->sum('total_amount');
            $latelyWechat[] = empty($latelyWechatVal)?0:$latelyWechatVal;
            //微信收入
//            $latelyBalanceVal = Db::name("tickets_order")->where(['pay_type'=>2,'currentDate'=>$v['currentDate']])->sum('total_amount');
//            $latelyBalance[] = empty($latelyBalanceVal)?0:$latelyBalanceVal;
            //微信收入
            $latelyDeliveryVal = Db::name("tickets_order")->where(['pay_type'=>3,'currentDate'=>$v['currentDate']])->sum('total_amount');
            $latelyDelivery[] = empty($latelyDeliveryVal)?0:$latelyDeliveryVal;
            //微信收入
//            $latelyAlipaytVal = Db::name("tickets_order")->where(['pay_type'=>4,'currentDate'=>$v['currentDate']])->sum('total_amount');
//            $latelyAlipayt[] = empty($latelyAlipaytVal)?0:$latelyAlipaytVal;

        }
        $this->assign("latelyValue",json_encode($latelyValue));
        $this->assign("latelyGeneral",json_encode($latelyGeneral));
        $this->assign("latelyWechat",json_encode($latelyWechat));
        $this->assign("latelyBalance",json_encode($latelyBalance));
        $this->assign("latelyDelivery",json_encode($latelyDelivery));
        $this->assign("latelyAlipayt",json_encode($latelyAlipayt));

        //月收入top5
        $where['is_pay'] = 2;
        $top = Db::name("tickets_order")->where($where)->field("sum(total_amount) as total,month")->limit(12)->group("month")->order("month asc")->select();
        $this->assign("top",$top);

        return $this->fetch('gather');
    }

    /**
     * 首页点击
     * @author zhixuedong
     * @date 2021/1/26/026
     */
    public function webClick(){
        try{
            $newData = date("Ymd",strtotime($_POST['data']));
            $value = $this->publicCount($newData);
            $weevalue = $this->weekCount($newData);
            $monthvalue = $this->publicCount($newData,1);
            $black['code'] = 0;
            $black['data'] = $value;
            $black['weedata'] = $weevalue;
            $black['monthvalue'] = $monthvalue;
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    public function accepted(){
        return $this->fetch('index');
    }

    public function clean(){
        try {
            $test = new Test();
            $test->clean();
            $black['code'] = 0;
            $black['msg'] = "清理成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

}